/*
 * @Author: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @Date: 2025-06-30 16:41:59
 * @LastEditors: 无聊 7989314+Hwz1997@user.noreply.gitee.com
 * @LastEditTime: 2025-09-24 09:16:28
 * @FilePath: \keep_motion_api\models\sport.model.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const { escapeRegex } = require('@/utils');

// 运动类型模型
const sportTypeSchema = new Schema({
  name: { type: String, required: true },
  body_part: [String],
  difficulty: { type: Number, min: 1, max: 5 },
  efficiency: Number,
  required_equipment: [String],
  calories_per_minute: Number
});
sportTypeSchema.statics.getSportType = async function (name, offset, limit) {
  try {
    const query = {};
    if (name) query.name = { $regex: escapeRegex(name), $options: 'i' };
    const rows = await this.find(query).skip(offset).limit(limit);
    const total = await this.countDocuments(query).exec();
    return { rows, total };
  } catch (error) {
    throw new Error('获取运动类型失败');
  }
}
sportTypeSchema.statics.createSportType = async function (params) {
  try {
    const sportType = new this(params);
    return await sportType.save();
  } catch (error) {
    throw new Error('创建运动类型失败');
  }
}
sportTypeSchema.statics.updateSportType = async function (id, params) {
  try {
    const sportType = await this.findByIdAndUpdate(id, params, { new: true });
    if (!sportType) throw new Error('运动类型不存在');
    return sportType;
  } catch (error) {
    throw new Error('更新运动类型失败');
  }
}
sportTypeSchema.statics.deleteSportType = async function (id) {
  try {
    const sportType = await this.findByIdAndDelete(id);
    if (!sportType) throw new Error('运动类型不存在');
    return sportType;
  } catch (error) {
    throw new Error('删除运动类型失败');
  }
}
module.exports = mongoose.model('SportType', sportTypeSchema);
